<template>
  <div class="position-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="部门名称">
          <el-input
            v-model="searchForm.departName"
            placeholder="请输入部门名称"
            clearable
            @clear="handleSearch"
          ></el-input>
        </el-form-item>
        <el-form-item label="岗位名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入岗位名称"
            clearable
            @clear="handleSearch"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="success" @click="handleAdd">新增岗位</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      style="width: 100%"
    >
      <el-table-column
        prop="departName"
        label="部门名称"
        min-width="120"
      ></el-table-column>
      <el-table-column
        prop="name"
        label="岗位名称"
        min-width="120"
      ></el-table-column>
      <el-table-column
        prop="duties"
        label="岗位职责"
        min-width="150"
      ></el-table-column>
      <el-table-column
        prop="description"
        label="岗位描述"
        min-width="150"
      ></el-table-column>
      <el-table-column
        prop="departDuties"
        label="部门职责"
        min-width="150"
      ></el-table-column>
      <el-table-column
        prop="departDescription"
        label="部门描述"
        min-width="150"
      ></el-table-column>
      <el-table-column
        prop="state"
        label="状态"
        width="80"
      >
        <template slot-scope="scope">
          <el-tag :type="scope.row.state === 0 ? 'success' : 'danger'">
            {{ scope.row.state === 0 ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="180"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleEdit(scope.row)"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            class="delete-btn"
            @click="handleDelete(scope.row)"
            :disabled="scope.row.isDeleted === 1"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <pagination
      :current-page.sync="pagination.current"
      :page-size.sync="pagination.size"
      :total="pagination.total"
      @pagination-change="fetchPositionData"
    />

    <!-- 添加/编辑岗位对话框 -->
    <el-dialog
      :title="editForm.id ? '编辑岗位' : '新增岗位'"
      :visible.sync="dialogVisible"
      width="500px"
      :close-on-click-modal="true"
      :modal-append-to-body="false"
      :append-to-body="true"
      :destroy-on-close="true"
    >
      <el-form
        ref="editForm"
        :model="editForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="部门" prop="departmentId">
          <department-tree-select
            v-model="editForm.departmentId"
            :disabled="!!editForm.id"
          />
        </el-form-item>
        <el-form-item label="岗位名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入岗位名称"></el-input>
        </el-form-item>
        <el-form-item label="岗位职责" prop="duties">
          <el-input
            type="textarea"
            v-model="editForm.duties"
            :rows="3"
            placeholder="请输入岗位职责"
          ></el-input>
        </el-form-item>
        <el-form-item label="岗位描述" prop="description">
          <el-input
            type="textarea"
            v-model="editForm.description"
            :rows="3"
            placeholder="请输入岗位描述"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">
          确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import DepartmentTreeSelect from '@/components/common/DepartmentTreeSelect.vue'
import Pagination from '@/components/common/Pagination.vue'

export default {
  name: 'OrgPositions',
  components: {
    DepartmentTreeSelect,
    Pagination
  },
  data() {
    return {
      loading: false,
      searchForm: {
        departName: '',
        name: ''
      },
      tableData: [],
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      dialogVisible: false,
      submitLoading: false,
      editForm: {
        id: '',
        departmentId: '',
        name: '',
        duties: '',
        description: '',
        state: 0
      },
      rules: {
        code: [
          { required: true, message: '请选择部门', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入岗位名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ]
      },
      departmentOptions: [] // 部门选项
    }
  },
  created() {
    this.fetchPositionData()
  },
  methods: {
    // 获取岗位数据
    async fetchPositionData() {
      try {
        this.loading = true
        const params = {
          current: this.pagination.current,
          size: this.pagination.size,
          departName: this.searchForm.departName || undefined,
          name: this.searchForm.name || undefined
        }
        
        const response = await this.$axios.get('/employee/station', { params })
        
        if (response && response.result === 200) {
          const { records, total, size, current } = response.data
          this.tableData = records
          this.pagination = {
            total,
            size,
            current
          }
        } else {
          this.$message.error(response.message || '获取岗位数据失败')
        }
      } catch (error) {
        console.error('获取岗位数据出错：', error)
        this.$message.error('获取岗位数据失败')
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.current = 1
      this.fetchPositionData()
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        departName: '',
        name: ''
      }
      this.handleSearch()
    },

    // 编辑岗位
    handleEdit(row) {
      this.editForm = {
        id: row.id,
        departmentId: row.code,
        name: row.name,
        duties: row.duties || '',
        description: row.description || '',
        state: row.state
      }
      
      this.dialogVisible = true

      this.$nextTick(() => {
        this.$refs.editForm.clearValidate()
      })
    },

    // 删除岗位
    handleDelete(row) {
      this.$confirm('确认删除该岗位吗？此操作不可恢复', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await this.$axios.delete('/employee/station', {
            params: { id: row.id }
          })
          
          if (response && response.result === 200) {
            this.$message.success('删除成功')
            // 重新获取数据
            await this.fetchPositionData()
          } else {
            this.$message.error(response.message || '删除失败')
          }
        } catch (error) {
          console.error('删除岗位出错：', error)
          this.$message.error('删除失败')
        }
      }).catch(() => {
        // 取消删除，不做任何操作
      })
    },

    // 新增岗位
    handleAdd() {
      this.editForm = {
        id: '',
        departmentId: '',
        name: '',
        duties: '',
        description: '',
        state: 0
      }
      this.dialogVisible = true
    },

    // 提交表单
    async submitForm() {
      try {
        await this.$refs.editForm.validate()
        this.submitLoading = true

        const response = await this.$axios.post('/employee/station', this.editForm)
        
        if (response && response.result === 200) {
          this.$message.success(this.editForm.id ? '修改成功' : '新增成功')
          // 先关闭对话框
          this.dialogVisible = false
          // 重置表单
          this.editForm = {
            id: '',
            code: '',
            name: '',
            duties: '',
            description: '',
            state: 0
          }
          // 重新获取数据
          await this.fetchPositionData()
        } else {
          this.$message.error(response.message || (this.editForm.id ? '修改失败' : '新增失败'))
        }
      } catch (error) {
        console.error('表单提交出错：', error)
        this.$message.error(this.editForm.id ? '修改失败' : '新增失败')
      } finally {
        this.submitLoading = false
        // 清除表单验证状态
        this.$nextTick(() => {
          this.$refs.editForm.clearValidate()
        })
      }
    }
  }
}
</script>

<style scoped>
.position-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  min-height: calc(100vh - 120px);
}

.search-bar {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.delete-btn {
  color: #F56C6C;
}

.delete-btn:hover {
  color: #f78989;
}

:deep(.el-table) {
  margin-top: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 0;
  margin-right: 20px;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-dialog__wrapper) {
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.department-dialog) {
  margin: 0 !important;
}

:deep(.v-modal) {
  opacity: 0.5;
  background: #000;
}
</style> 